package fty.baymax.experiment.support;

import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.*;

/**
 * @Author: 710524
 * @Date: 2020-10-23 15:29
 * @Description: TODO
 */
public class ThreadExecutor extends ThreadPoolExecutor {

    public ThreadExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, new ArrayBlockingQueue<Runnable>(maximumPoolSize));
    }

    public ThreadExecutor(int maximumPoolSize) {
        super(maximumPoolSize, maximumPoolSize, 200, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(maximumPoolSize));
    }

    public void execute(Runnable command, int times) {
        for (int i = 0; i < times; i++) {
            super.execute(command);
        }
    }

    public Collection<Future<?>> submit(Runnable task, int times) {
        Collection<Future<?>> collection = new ArrayList<Future<?>>(times);
        for (int i = 0; i < times; i++) {
            collection.add(submit(task));
        }
        return collection;
    }

    public <T> Collection<Future<T>> submit(Callable<T> task, int times) {
        Collection<Future<T>> collection = new ArrayList<Future<T>>(times);
        for (int i = 0; i < times; i++) {
            collection.add(submit(task));
        }
        return collection;
    }

    public void wait(Collection<Future<?>> collection) {
        for (Future<?> future : collection) {
            try{
                future.get();
            }catch (Exception e){
            }
        }
    }

}
